package com.ruoyi.tzzl.service.imp;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.tzzl.domain.WzBalanceChangeRecord;
import com.ruoyi.tzzl.domain.WzMatchmakerLevel;
import com.ruoyi.tzzl.domain.WzOrder;
import com.ruoyi.tzzl.domain.WzProgramUser;
import com.ruoyi.tzzl.domain.dto.MonthDto;
import com.ruoyi.tzzl.domain.vo.QueryVo;
import com.ruoyi.tzzl.mapper.WzOrderMapper;
import com.ruoyi.tzzl.service.*;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 订单Service业务层处理
 * @author by caoyong
 * @date 2022/11/17
 **/
@Slf4j
@Service
public class WzOrderServiceImpl extends ServiceImpl<WzOrderMapper, WzOrder> implements IWzOrderService {

    @Autowired
    private WzOrderMapper orderMapper;
    @Autowired
    private IWzProgramUserService wzProgramUserService;
    @Autowired
    private IWzMatchmakerLevelService wzMatchmakerLevelService;
    @Autowired
    private IWzPayConfigService wzPayConfigService;
    @Autowired
    private IWzBalanceChangeRecordService balanceChangeRecordService;
    @Autowired
    private RedisCache redisCache;


    @Override
    public List<WzOrder> selectWzOrderList(QueryVo queryVo) {
        LambdaQueryWrapper<WzOrder> lqw = new LambdaQueryWrapper<>();
        //订单类型
        if (ObjectUtils.isNotEmpty(queryVo.getOrderType())) {
            lqw.eq(WzOrder::getOrderType, queryVo.getOrderType());
        }
        //下单时间
        if (ObjectUtils.isNotEmpty(queryVo.getStartTime())) {
            lqw.between(WzOrder::getCreateTime, queryVo.getStartTime(), queryVo.getEndTime());
        }
        //订单号
        if (ObjectUtils.isNotEmpty(queryVo.getOrderNumber())) {
            lqw.eq(WzOrder::getOrderNumber, queryVo.getOrderNumber());
        }
        //用户id
        if (ObjectUtils.isNotEmpty(queryVo.getWid())){
            lqw.eq(WzOrder::getWid,queryVo.getWid());
        }
        return this.list(lqw);
    }

    /**
     * 查询订单数据
     */
    @Override
    public Map<String, Object> orderData() {
        Map<String, Object> map = new HashMap<>();
        //会员开通金额
        Integer membersSum = orderMapper.orderSum(1L);
        map.put("membersSum", membersSum);
        //邀约订单金额
        Integer invitationSum = orderMapper.orderSum(4L);
        map.put("invitationSum", invitationSum);
        //聊天订单金额
        Integer chatSum = orderMapper.orderSum(2L);
        map.put("chatSum", chatSum);
        //视频订单金额
        Integer videoSum = orderMapper.orderSum(3L);
        map.put("videoSum", videoSum);
        return map;
    }

    /**
     * 查询订单交易金额
     */
    @Override
    public List<WzOrder> orderAmount(Long type) {
        //查询全部订单
        if (type==1){
            return this.list();
        }else if(type==2){ //查询当天订单
            LambdaQueryWrapper<WzOrder> lqw = new LambdaQueryWrapper<>();
            lqw.between(WzOrder::getCreateTime, DateUtils.DateToString(new Date()), DateUtils.DateToString(DateUtils.addTime(new Date(), 1)));
            List<WzOrder> todayOrder = this.list(lqw);
            return todayOrder;
        }else { //查询当月订单
            LambdaQueryWrapper<WzOrder> theMonthOrderLqw = new LambdaQueryWrapper<>();
            theMonthOrderLqw.between(WzOrder::getCreateTime, DateUtils.monthFirstDay(), DateUtils.addTime(DateUtils.stringToDate(DateUtils.monthLastDay()), 1));
            List<WzOrder> theMonthOrder = this.list(theMonthOrderLqw);
            return theMonthOrder;
        }

    }

    /**
     * 根据订单号查询订单信息
     *
     * @param orderNumber
     */
    @Override
    public WzOrder getByOrderNumber(String orderNumber) {
        LambdaQueryWrapper<WzOrder> lqw =new LambdaQueryWrapper<>();
        lqw.eq(WzOrder::getOrderNumber,orderNumber);
        return this.getOne(lqw);
    }

    /**
     * 查询总成交金额和当日成交金额
     */
    @Override
    public Map<String, Object> sumAmount() {
        Map<String, Object> map = new HashMap<>();
        //查询总成交金额
        Integer sum = orderMapper.orderSum(10L);
        map.put("sum", sum);
        //查询当天成交额
        Integer toDays = orderMapper.toDays();
        map.put("toDays", toDays);
        return map;
    }

    /**
     * 提交订单
     *
     * @param wzOrder
     */
    @Override
    @Transactional
    public boolean addOrder(WzOrder wzOrder) {
        //用户信息
        WzProgramUser user = wzProgramUserService.getById(wzOrder.getWid());

        //查询推荐团队
        WzProgramUser recommendUser =wzProgramUserService.getById(wzOrder.getInvitationCode());
        //查询直属红娘
        WzProgramUser inviterUser = wzProgramUserService.getById(user.getInviterId());
        WzProgramUser theUser =null;
         if (ObjectUtils.isNotEmpty(inviterUser)){
             theUser = wzProgramUserService.getById(inviterUser.getMatchmakerId());
         }
        //订单
        WzOrder order =new WzOrder();
        //查询直属红娘等级
       List<WzMatchmakerLevel> list = wzMatchmakerLevelService.list();
       //直属红娘等级
        Long level =1L;
        if (ObjectUtils.isNotEmpty(theUser)){
            for (int i = 0; i < list.size(); i++) {
                if (theUser.getMembersNumber()>=list.get(i).getUpgrade()){
                    level =Long.parseLong(list.get(i).getLevel());
                }
            }
        }
        WzProgramUser jtUser =null;
        if (ObjectUtils.isNotEmpty(recommendUser)){
            jtUser = wzProgramUserService.getById(recommendUser.getMatchmakerId());
        }
        //间推红娘等级
        Long jtLevel =1L;
        if (ObjectUtils.isNotEmpty(jtUser)){
            for (int i = 0; i < list.size(); i++) {
                if (jtUser.getMembersNumber()>=list.get(i).getUpgrade()){
                    jtLevel =Long.parseLong(list.get(i).getLevel());
                }
            }
        }

        //订单类型
        switch (wzOrder.getOrderType()){
            case "1": //开通会员
                membership(wzOrder, user, recommendUser, theUser, order, level, jtLevel);
                break;
            case "2": //付费聊天订单
                chatOrder(wzOrder, user, theUser, order, level, list);
                userBalanceRecord(user, order, 8, "用户付费聊天订单扣款");
                break;
            case "3": //付费视频订单
                chatOrder(wzOrder, user, theUser, order, level ,list);
                userBalanceRecord(user, order, 9, "用户付费视频订单扣款");
                break;
            case "6": //邀约订单
                invitation(wzOrder, user, theUser, order ,level);
                break;
        }
        return true;
    }

    /**
     * 查看邀约订单
     */
    @Override
    public List<WzOrder> invitationOrder(WzOrder wzOrder) {
        LambdaQueryWrapper<WzOrder> lqw =new LambdaQueryWrapper<>();
        lqw.eq(WzOrder::getOrderType,"6");
        if (ObjectUtils.isNotEmpty(wzOrder.getState())){
            lqw.eq(WzOrder::getState,wzOrder.getState());
        }
        lqw.between(WzOrder::getCreateTime,DateUtils.DateToString(new Date()),DateUtils.DateToString(DateUtils.addTime(new Date(),1)));
        return this.list(lqw);
    }

    /**
     * 查看全部邀约订单
     */
    @Override
    public List<WzOrder> invitationOrder() {
        LambdaQueryWrapper<WzOrder> lqw =new LambdaQueryWrapper<>();
        lqw.eq(WzOrder::getOrderType,"6");
        return this.list(lqw);
    }

    /**
     * 查询交易总金额
     */
    @Override
    public int sumMoney() {
        List<WzOrder> list =this.list();
        int sumMoney =0;
        for (int i = 0; i < list.size(); i++) {
            sumMoney += list.get(i).getPayFriendc();
        }
        return sumMoney;
    }

    /**
     * 查询今年每个月的记录
     */
    @Override
    public Map<String, Object> yearMonthRecord() {
     Map<String,Object> map =new HashMap<>();
     //获取当前年份
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        //查询每月新增用户
       MonthDto addingaUser = orderMapper.addingaUser(year);
       map.put("addingaUser",addingaUser);
       //每月新增付费会员
        MonthDto payMembers =orderMapper.payMembers(year);
        map.put("payMembers",payMembers);
        //每月新增邀约订单
        MonthDto invitationOrder =orderMapper.invitationOrder(year);
        map.put("invitationOrder",invitationOrder);
        //查询每月交易金额
        MonthDto tradingMoney =orderMapper.tradingMoney(year);
        map.put("tradingMoney",tradingMoney);
        return map;
    }

    /**
     * 查询用户分销订单记录
     */
    @Override
    public List<WzBalanceChangeRecord> orderRecord(WzBalanceChangeRecord wzBalanceChangeRecord) {
       LambdaQueryWrapper<WzBalanceChangeRecord> lqw =new LambdaQueryWrapper<>();
       lqw.eq(WzBalanceChangeRecord::getWid,wzBalanceChangeRecord.getWid());
       if (ObjectUtils.isNotEmpty(wzBalanceChangeRecord.getType())){
           switch (wzBalanceChangeRecord.getType().toString()){
               case "1":
                   lqw.eq(WzBalanceChangeRecord::getType,"1");
                   break;
               case "2":
                   lqw.in(WzBalanceChangeRecord::getType,"2","3");
                   break;
               case "3":
                   lqw.in(WzBalanceChangeRecord::getType,"4","5");
                   break;
               case "4":
                   lqw.eq(WzBalanceChangeRecord::getType,"6");
                   break;
           }
       }
       return balanceChangeRecordService.list(lqw);
    }

    /**
     * 查看团队邀约订单信息
     * */
    @Override
    public List<WzOrder> userInvitationOrder(Long id) {
        LambdaQueryWrapper<WzOrder> lqw =new LambdaQueryWrapper<>();
        lqw.eq(WzOrder::getOrderType,"6");
        lqw.in(WzOrder::getAboutDirectlyUid,id);
        return this.list(lqw);
    }

    /**
     * 确认邀约订单
     *
     * @param order
     */
    @Override
    public boolean confirmOrder(WzOrder order) {
         WzOrder wzOrder =this.getByOrderNumber(order.getOrderNumber());
         if (order.getState().equals("1")){ //成功
             wzOrder.setState("1");
             //订单成功奖励红娘佣金
             return  this.updateById(wzOrder);
         }else{ //失败
             wzOrder.setState("2");
             //订单失败退回用户友币
             return this.updateById(wzOrder);
         }
    }

    /**
     * 查询会员管理记录
     */
    @Override
    public List<WzOrder> membershipManagement(WzOrder wzOrder) {
        LambdaQueryWrapper<WzOrder> lqw =new LambdaQueryWrapper<>();
       lqw.eq(WzOrder::getOrderType,"1");
       //用户名称
       if (ObjectUtils.isNotEmpty(wzOrder.getUserName())){
           lqw.eq(WzOrder::getUserName,wzOrder.getUserName());
       }
       //红娘名称
        if (ObjectUtils.isNotEmpty(wzOrder.getDirectlyMatchmaker())){
            lqw.like(WzOrder::getDirectlyMatchmaker,wzOrder.getDirectlyMatchmaker());
        }
        //团队人员
        if (ObjectUtils.isNotEmpty(wzOrder.getTeamMembers())){
          WzProgramUser user =  wzProgramUserService.getByName(wzOrder.getTeamMembers());
          if (ObjectUtils.isEmpty(user)){
              List<WzOrder> list =new ArrayList<>();
          return list;
          }
            WzProgramUser programUser = wzProgramUserService.getById(user.getMatchmakerId());
            lqw.like(WzOrder::getTeamMatchmaker,programUser.getUserName());
        }
       List<WzOrder> list = this.list(lqw);
        return list;
    }

    /**
     * 是否存在与该用户聊天
     *
     * @param wid
     * @param beUserId
     */
    @Override
    public boolean doesExistChat(Long wid, Long beUserId) {
        LambdaQueryWrapper<WzOrder> lqw = new LambdaQueryWrapper<>();
        lqw.eq(WzOrder::getWid,wid);
        lqw.eq(WzOrder::getBeUserId,beUserId);
        if (this.list(lqw).size() == 0) {
            return false;
        }else{
            return true;
        }
    }

    /**
     * 查看红娘邀约订单完成单量
     *
     * @param id
     */
    @Override
    public Integer invitationOrders(Long id) {
        LambdaQueryWrapper<WzOrder> lqw =new LambdaQueryWrapper<>();
        lqw.eq(WzOrder::getOrderType,6);
        lqw.eq(WzOrder::getAboutDirectlyUid,id);
        lqw.eq(WzOrder::getState,"1");
        return this.list().size();
    }


    //生成邀约订单
    private void invitation(WzOrder wzOrder, WzProgramUser user, WzProgramUser theUser, WzOrder order, Long level) {
        order.setOrderNumber(IdUtils.get16UUID("YY"));//订单编号
        order.setOrderType(wzOrder.getOrderType()); //订单类型
        order.setUserName(user.getUserName()); //用户姓名
        order.setUserAvatar(user.getAvatarurl()); //用户头像
        order.setPhone(user.getPhone()); //手机号码
        order.setSex(user.getSex()); //性别
        order.setWid(user.getId()); //下单用户id
        //直属红娘
        if (ObjectUtils.isNotEmpty(theUser)){
           WzMatchmakerLevel matchmakerLevel = wzMatchmakerLevelService.getByLevel(level); //等级信息
            order.setDirectlyMatchmaker(theUser.getUserName()+matchmakerLevel.getInvitationOrder()+"%"); //直属红娘姓名+奖励百分比
            Double commission = wzOrder.getPayFriendc().doubleValue() * (matchmakerLevel.getMemberRewards().doubleValue() / 100); //佣金计算 支付友币*奖励百分比
            order.setDirectlyCommission(commission);
            userRecord(user,theUser,order,commission,6,"直属红娘邀约订单收益");
        }else{
            order.setDirectlyMatchmaker("平台");
        }
        //邀约信息
        WzProgramUser  aboutUser = wzProgramUserService.getById(wzOrder.getAboutUserId()); //被邀约用户信息
        JSONObject jsonObject =new JSONObject();
        jsonObject.put("userName", aboutUser.getUserName()); //被邀约用户姓名
        jsonObject.put("phone",aboutUser.getPhone()); //被邀约用户手机号码)
        jsonObject.put("avatarurl", aboutUser.getAvatarurl()); //被邀约用户头像)
        order.setInvitationMessage(jsonObject.toString());  //邀约信息
        order.setAboutUserId(aboutUser.getId()); //被邀约用户id
        order.setAboutDirectlyUid(aboutUser.getMatchmakerId());//被约用户红娘id
        order.setPayFriendc(wzOrder.getPayFriendc()); //支付友币
        order.setCreateTime(new Date()); //创建时间
        userBalanceRecord(user,order,12,"用户邀约订单扣款");
        this.save(order);
    }


    /**付费聊天或者视频订单*/
    private void chatOrder(WzOrder wzOrder, WzProgramUser user, WzProgramUser theUser, WzOrder order, Long level,List<WzMatchmakerLevel> list) {
        if (wzOrder.getOrderType().equals("2")){
            order.setOrderNumber(IdUtils.get16UUID("LT")); //订单编号
        }else if (wzOrder.getOrderType().equals("3")){
            order.setOrderNumber(IdUtils.get16UUID("SP")); //订单编号
        }
        order.setWid(user.getId()); //用户id
        order.setBeUserId(wzOrder.getBeUserId()); //被聊用户id
        order.setOrderType(wzOrder.getOrderType()); //订单类型
        order.setUserName(user.getUserName()); //用户名称
        order.setUserAvatar(user.getAvatarurl()); //微信头像
        order.setPhone(user.getPhone()); //手机号
        order.setSex(user.getSex()); //性别
        order.setPayFriendc(wzOrder.getPayFriendc()); //支付友币
        order.setCreateTime(new Date()); //创建时间
        //直属红娘
        if (ObjectUtils.isNotEmpty(theUser)) {
           WzMatchmakerLevel zsMatchmakerLevel = wzMatchmakerLevelService.getByLevel(level); //红娘等级信息
            order.setDirectlyMatchmaker(theUser.getUserName()+zsMatchmakerLevel.getMemberRewards()+"%"); //直属红娘姓名+奖励百分比
            Double commission = wzOrder.getPayFriendc().doubleValue() * (zsMatchmakerLevel.getMemberRewards().doubleValue() / 100); //佣金计算 支付友币*奖励百分比
            order.setDirectlyCommission(commission); //直属佣金
            if (wzOrder.getOrderType().equals("2")){
                //聊天扣费并增加记录
                userBalanceRecord(user,order,8,"用户聊天订单扣款");
                userRecord(user,theUser,order,commission,2,"直属红娘聊天订单收益");
            }else if (wzOrder.getOrderType().equals("3")){
                userBalanceRecord(user,order,9,"用户视频订单扣款");
                userRecord(user,theUser,order,commission,3,"直属红娘视频订单收益");
            }
        } else {
            order.setDirectlyMatchmaker("平台");
        }
        this.save(order);

        //被聊订单
        WzOrder wzOrder1 = new WzOrder();
        //被聊用户信息
        WzProgramUser beUser = wzProgramUserService.getById(wzOrder.getBeUserId());
        if (wzOrder.getOrderType().equals("2")){
            wzOrder1.setOrderNumber(IdUtils.get16UUID("BL")); //订单编号
            wzOrder1.setOrderType("4"); //订单类型
        }else if (wzOrder.getOrderType().equals("3")){
            wzOrder1.setOrderNumber(IdUtils.get16UUID("BSP")); //订单编号
            wzOrder1.setOrderType("5"); //订单类型
        }
        wzOrder1.setUserName(beUser.getUserName()); //用户姓名
        wzOrder1.setUserAvatar(beUser.getAvatarurl()); //用户头像
        wzOrder1.setSex(beUser.getSex()); //性别
        wzOrder1.setPhone(beUser.getPhone()); //手机号码
        wzOrder1.setWid(beUser.getId()); //用户id
        //直属红娘
        WzProgramUser zsUser = wzProgramUserService.getById(beUser.getInviterId());
        if (ObjectUtils.isNotEmpty(zsUser)) {
            Long grade =1L;
            for (int i = 0; i < list.size(); i++) {
                if (zsUser.getMembersNumber()>=list.get(i).getUpgrade()){
                    grade =Long.parseLong(list.get(i).getLevel());
                }
            }
           WzMatchmakerLevel matchmakerLevel = wzMatchmakerLevelService.getByLevel(grade); //等级信息
            wzOrder1.setDirectlyMatchmaker(zsUser.getUserName()+matchmakerLevel.getBeChatpayReward()+"%");//上级姓名+直推用户被付费聊天奖励,百分比
            Double commission =wzOrder.getPayFriendc().doubleValue() * (matchmakerLevel.getBeChatpayReward().doubleValue() / 100);
           wzOrder1.setDirectlyCommission(commission); //直属佣金
            if (wzOrder.getOrderType().equals("2")){
                userRecord(user,zsUser,order,commission,4,"直属红娘被聊天订单");
            }else if (wzOrder.getOrderType().equals("3")){
                userRecord(user,zsUser,order,commission,5,"直属红娘被视频订单");
            }
        } else {
            wzOrder1.setDirectlyMatchmaker("平台");
        }
        wzOrder1.setPayFriendc(wzOrder.getPayFriendc()); //支付友币
        wzOrder1.setCreateTime(new Date()); //创建时间

        this.save(wzOrder1);
    }

    /**开通会员订单*/
    private void membership(WzOrder wzOrder, WzProgramUser user, WzProgramUser recommendUser, WzProgramUser theUser, WzOrder order,Long level,Long jtLevel) {
        order.setUserAvatar(user.getAvatarurl()); //用户头像
        order.setOrderNumber(IdUtils.get16UUID("HY")); //订单编号
        order.setOrderType(wzOrder.getOrderType()); //订单类型
        order.setWid(wzOrder.getWid());
        order.setUserName(user.getUserName()); //用户名称
        order.setPhone(user.getPhone()); //手机号
        order.setSex(user.getSex()); //性别
        WzMatchmakerLevel zsMatchmakerLevel = wzMatchmakerLevelService.getByLevel(level); //查询佣金比例
        WzMatchmakerLevel jtMatchmakerLevel =wzMatchmakerLevelService.getByLevel(jtLevel); //间推佣金比例
        //直属红娘
        if (ObjectUtils.isNotEmpty(theUser)) {
            order.setDirectlyMatchmaker(theUser.getUserName()+"," + zsMatchmakerLevel.getMemberRewards() + "%");  //直属红娘+奖励百分比
            Double commission = wzOrder.getPayFriendc().doubleValue() * (zsMatchmakerLevel.getMemberRewards().doubleValue() / 100); //佣金计算
            order.setDirectlyCommission(commission); //直属佣金
            order.setDirectlyMatchmakerAvatar(theUser.getAvatarurl()); //直属红娘头像
            //给红娘增加佣金,并添加余额变更记录
            userRecord(user, theUser, order, commission, 1, "直属红娘开通会员订单");
        } else {
            order.setDirectlyMatchmaker("平台");
            order.setDirectlyMatchmakerAvatar("https://tzz.funongkj.com/profile/upload/2022/12/05/微信图片_20221205163903_20221205164010A001.png"); //默认平台头像
        }
        //推荐团队
        if (ObjectUtils.isNotEmpty(recommendUser)) {
            order.setRecommendTeam(recommendUser.getUserName()+"," + zsMatchmakerLevel.getTeamCommission() + "%"); ////直属团队+奖励百分比
            Double commission = wzOrder.getPayFriendc().doubleValue() * (zsMatchmakerLevel.getTeamCommission().doubleValue() /100); //佣金计算
            order.setRecommendCommission(commission);
            //添加红娘发展会员人数
            WzProgramUser reUser = wzProgramUserService.getById(recommendUser.getMatchmakerId()); //红娘用户信息
            reUser.setMembersNumber(reUser.getMembersNumber() + 1);
            wzProgramUserService.updateById(reUser);
            //给用户增加佣金,并添加余额变更记录
            userRecord(user, recommendUser, order, commission, 1, "推荐团队佣金收益");
        } else {
            order.setRecommendTeam("无");
            //不属于任何红娘,用户
        }
        //团队红娘
        if (ObjectUtils.isNotEmpty(recommendUser) && ObjectUtils.isNotEmpty(recommendUser.getMatchmakerId())) {
            WzProgramUser teamUser = wzProgramUserService.getById(recommendUser.getMatchmakerId());
            order.setTeamMatchmaker(teamUser.getUserName()+"," + jtMatchmakerLevel.getBetweenRewards() + "%"); //团队红娘姓名+奖励百分比
            Double commission = wzOrder.getPayFriendc().doubleValue() * (jtMatchmakerLevel.getBetweenRewards().doubleValue() /100); //佣金计算 支付友币*百分之四十
            order.setTeamCommission(commission); //团队红娘佣金
             //给用户增加佣金,并添加余额变更记录
            userRecord(user, teamUser, order, commission, 1, "团队红娘佣金收益");
        } else {
            order.setTeamMatchmaker("无");
        }
        order.setPayFriendc(wzOrder.getPayFriendc()); //支付友币
        order.setCreateTime(new Date()); //创建时间
        //记录用户下单操作
        userBalanceRecord(user, order, 7, "用户充值会员订单扣款");
        //将会员过期时间添加到redis
        redisMembers(wzOrder, user);
        this.save(order);
    }

    /**将会员过期时间添加到redis*/
    private void redisMembers(WzOrder wzOrder, WzProgramUser user) {
        if (wzOrder.getRenewal().equals("2")){ //开通会员
            String key ="KTHY"+user.getId();
            if (wzOrder.getTypeOfMember().equals("1")){ //季卡
                redisCache.setCacheObject(key,key,7879680, TimeUnit.SECONDS); //过期时间单位为秒
            }else{ //年卡
                redisCache.setCacheObject(key,key,31536000, TimeUnit.SECONDS);
            }
        }else{ //续费
            String key ="KTHY"+user.getId();
            //先查一下是否存在redis
           long time = redisCache.getExpire(key);
           if (time == -2){
              //已经过期重新续费
               if (wzOrder.getTypeOfMember().equals("1")){ //季卡
                   redisCache.setCacheObject(key,key,7879680, TimeUnit.SECONDS); //过期时间单位为秒
               }else{ //年卡
                   redisCache.setCacheObject(key,key,31536000, TimeUnit.SECONDS);
               }
           }else{
               //还存在redis，续费添加过期时间
               redisCache.deleteObject(key);
               if (wzOrder.getTypeOfMember().equals("1")){ //季卡
                   redisCache.setCacheObject(key,key, (int) (7879680+time), TimeUnit.SECONDS); //过期时间单位为秒
               }else{ //年卡
                   redisCache.setCacheObject(key,key, (int) (31536000+time), TimeUnit.SECONDS);
               }
           }
           log.info("用户:{}会员到期时间还剩:{}",user.getUserName(),time);
        }
    }


    /**
     * 用户下单操作
     * */
    private void userBalanceRecord(WzProgramUser user, WzOrder order, Integer type, String note) {
        user.setFriendc(user.getFriendc() - order.getPayFriendc());
        if (type ==7){
            user.setRole("2"); //用户角色
            user.setUserLevel("2"); //用户等级(1-普通用户 2-年费会员)
        }
        wzProgramUserService.updateById(user);
        WzBalanceChangeRecord balanceChangeRecord =new WzBalanceChangeRecord();
        balanceChangeRecord.setType(type); //记录类型
        balanceChangeRecord.setWname(user.getUserName()); //用户名称
        balanceChangeRecord.setWid(user.getId()); //用户id
        balanceChangeRecord.setNote(note);//备注
        balanceChangeRecord.setOrderNumber(order.getOrderNumber()); //订单号
        balanceChangeRecord.setCreateTime(new Date()); //创建时间
        balanceChangeRecord.setBalance(user.getFriendc().doubleValue());//余额
        balanceChangeRecord.setChangeMoney(order.getPayFriendc().doubleValue()); //变动余额
        balanceChangeRecordService.save(balanceChangeRecord);
    }

    /**
     * 给红娘增加佣金,并添加余额变更记录
     * user 下单用户信息  theUser红娘信息  order 订单信息  commission佣金金额  type记录类型  note备注
     */
    private void userRecord(WzProgramUser user, WzProgramUser theUser, WzOrder order, Double commission, Integer type, String note) {
        theUser.setCarryCommission(theUser.getCarryCommission() + commission); //佣金
        //添加佣金
        wzProgramUserService.updateById(theUser);
        WzBalanceChangeRecord wzBalanceChangeRecord = new WzBalanceChangeRecord();
        wzBalanceChangeRecord.setChangeMoney(commission); //变动金额
        wzBalanceChangeRecord.setCommission(theUser.getCarryCommission()); //佣金
        wzBalanceChangeRecord.setBalance(theUser.getFriendc().doubleValue()); //余额
        wzBalanceChangeRecord.setCreateTime(new Date()); //创建时间
        wzBalanceChangeRecord.setOrderNumber(order.getOrderNumber()); //订单编号
        wzBalanceChangeRecord.setType(type); //记录类型
        wzBalanceChangeRecord.setNote(note); //备注
        wzBalanceChangeRecord.setWid(theUser.getId()); //用户id
        wzBalanceChangeRecord.setWname(theUser.getUserName()); //用户姓名
        wzBalanceChangeRecord.setEarningsSource(user.getUserName());//收益来源用户姓名
        wzBalanceChangeRecord.setSourceId(user.getId()); //收益来源用户id
        //添加记录
        balanceChangeRecordService.save(wzBalanceChangeRecord);
    }


}
